package org.framework.lazy.cloud.network.heartbeat.server.netty.permeate.tcp.handler;


import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOption;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.framework.lazy.cloud.network.heartbeat.common.NettyByteBuf;
import org.framework.lazy.cloud.network.heartbeat.common.utils.ChannelAttributeKeyUtils;

/**
 * 来自客户端 真实服务器返回的数据请求
 */
@Slf4j
public class NettyTcpServerPermeateServerRealHandler extends SimpleChannelInboundHandler<NettyByteBuf> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 根据访客ID 确认真实通道 读写打开
        Channel channel = ctx.channel();
        Channel nextChannel = ChannelAttributeKeyUtils.getNextChannel(channel);

        channel.config().setOption(ChannelOption.AUTO_READ, true);
        super.channelActive(ctx);
    }



    @Override
    public void channelRead0(ChannelHandlerContext ctx,NettyByteBuf nettyByteBuf) {

        Channel channel = ctx.channel();
        byte[] bytes = nettyByteBuf.getData();
        log.debug("bytes.length:{}",bytes.length);
        log.debug("接收客户端真实服务数据:{}", new String(bytes));
        Channel nextChannel = ChannelAttributeKeyUtils.getNextChannel(channel);
        // 将二进制数组转换成 ByteBuf 然后进行发送
        ByteBuf realBuf = nextChannel.config().getAllocator().buffer(bytes.length);
        realBuf.writeBytes(bytes);

        nextChannel.writeAndFlush(realBuf);
    }



    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        //  客户端真实通信通道
        Channel nextChannel = ChannelAttributeKeyUtils.getNextChannel(ctx.channel());
        if (nextChannel != null) {
            // 上报关闭这个客户端的访客通道
            nextChannel.close();
        }

        super.channelInactive(ctx);
    }

    @Override
    public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {


        // 获取访客的传输通道
        Channel nextChannel = ChannelAttributeKeyUtils.getNextChannel(ctx.channel());
        if (nextChannel != null) {
            log.debug("transfer AUTO_READ:{} ",ctx.channel().isWritable());
            nextChannel.config().setOption(ChannelOption.AUTO_READ, ctx.channel().isWritable());
        }

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }
}